<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>LifeCycle</title>
    </head>
    <body>
        <div id="app">
            <div v-draggable:absolute="styleObj">{{name}}</div>
        </div>
        <script src="my-vue.js"></script>
        <script>  
        Vue.directive('draggable',{//def
            bind(el,binding){
                console.log('binding',binding);
                if(binding.modifiers.disabled){
                    return;
                }
                el.style.position = binding.arg || 'absolute';
                //获取绑定到此DOM元素上的样式对象
                let {value:styleObj} = binding;
                //遍历对象上的属性
                for(let key in styleObj){
                    el.style[key]=styleObj[key];
                }
                //是否正在拖拽中
                let isDragging = false;
                let offsetX,offsetY;
                let isCtrl=false;
                //给DOM元素添加事件监听
                el.addEventListener('mousedown',(event)=>{
                    //如果当前需要按下ctrl键，便是没有按下
                    if(binding.modifiers.ctrl && !isCtrl){
                        return ;
                    }
                    offsetX=event.offsetX;
                    offsetY=event.offsetY;
                    isDragging=true;
                });
                el.addEventListener('mousemove',(event)=>{
                    if(isDragging){
                        el.style.left = (event.clientX - offsetX)+'px';
                        el.style.top = (event.clientY - offsetY)+'px';
                    }
                });
                el.addEventListener('mouseup',(event)=>{
                    isDragging=false;
                });
                el.handleKeydown = (event)=>{
                    if(event.key === 'Control') isCtrl=true;
                };
                document.addEventListener('keydown',el.handleKeydown);
                el.handleKeyup = (event)=>{
                    if(event.key === 'Control') isCtrl=true;
                };
                document.addEventListener('keyup',el.handleKeyup);
            },
            unbind(){
                document.removeEventListener('keydown',el.handleKeydown);
                document.removeEventListener('keyup',el.handleKeyup);
            }
        });
        var vm = new Vue({
            el:'#app',
            data:{
                name:'zhangsan',
                styleObj:{
                    width:'100px',
                    height:'100px',
                    backgroundColor: 'green'
                }
            },
        });
    </script>
    </body>
</html>